<template>
  <div style="padding: 20px">
    <div style="margin-bottom: 10px">
      <a-select
          ref="select"
          v-model:value="params.tabStatus"
          class="item"
          :options="options1"
          :placeholder="$t('订单状态')"
      />
      <a-select
          ref="select"
          v-model:value="params.channel"
          class="item"
          :options="options2"
          :placeholder="$t('订单来源')"
      />
      <a-select
          ref="select"
          v-model:value="params.timeType"
          class="item"
          :options="options3"
          style="margin-right: 0"
          @change="handleChange"
          :placeholder="$t('下单时间')"
      />
      <a-range-picker style="width: 360px" inputReadOnly
                      :value-format="params.timeType === 3?'YYYY-MM-DD':'YYYY-MM-DD HH:mm:ss'"
                      class="item"
                      v-model:value="params.time" :show-time="params.timeType !== 3"/>
      <a-select
          ref="select"
          v-model:value="params.keywordType"
          class="item"
          style="margin-right: 0;width: 80px"
          :options="options4"
      />
      <a-input style="width: 180px" :placeholder="$t('请输入')" class="item"
               v-model:value="params.keyword"
               placeholder="Basic usage"/>
      <a-button :loading="loading" class="item" danger type="primary" @click="handleReset">重置
      </a-button>
      <a-button :loading="loading" class="item" danger type="primary" @click="getList">查询</a-button>

    </div>

    <a-table :customRow="customRow" size="middle" :sticky="true" :loading="loading" bordered
             :pagination="false"
             rowKey="tableOpId"
             :scroll="{ x: 1700 }"
             :dataSource="data" :columns="columns">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'oper'">
          <a-button
              @click.stop="clickListener(record, ClickTypeEnum.kfp)"
              v-if="record.tabStatus === OrderTabStatusEnum.Done &&(!record.splitType ||(record.splitType && record.parentId > 0))"
              type="link" danger>
            {{ $t('开发票') }}
          </a-button>
          <a-button
              @click.stop="clickListener(record, ClickTypeEnum.kfp)"
              v-if="record.tabStatus !== OrderTabStatusEnum.Cancel &&record.tabStatus !== OrderTabStatusEnum.Unpay"
              type="link" danger> {{ $t('打印小票') }}
          </a-button>
          <a-dropdown
              v-if="record.tabStatus === OrderTabStatusEnum.Done &&(!record.splitType ||(record.splitType && record.children))">
            <a-button type="link" danger @click.stop>
              {{ $t('退单/退菜') }}
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <a-button @click.stop="clickListener(record, ClickTypeEnum.zdt)">
                    {{ $t('整单退') }}
                  </a-button>
                </a-menu-item>
                <a-menu-item @click.stop="clickListener(record, ClickTypeEnum.zdtfz)">
                  <a-button v-if="record.splitType && record.children">
                    {{ $t('整单退并复制') }}
                  </a-button>
                </a-menu-item>
                <a-menu-item @click.stop="clickListener(record, ClickTypeEnum.bftc)">
                  <a-button v-if="!record.splitType">
                    {{ $t('部分退菜') }}
                  </a-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <a-button @click.stop="clickListener(record, ClickTypeEnum.qjz)"
                    v-if="record.tabStatus === OrderTabStatusEnum.Unpay" type="link" danger>
            {{ $t('去结账') }}
          </a-button>
          <a-button @click.stop="clickListener(record, ClickTypeEnum.fjz)"
                    v-if="record.tabStatus === OrderTabStatusEnum.Done &&!record.splitType"
                    type="link" danger> {{ $t('反结账') }}
          </a-button>
        </template>
        <template v-else-if="column.dataIndex === 'tableName'">
          <div class="flex justify-between items-center flex-1">
            <span>{{ record.tableName }}</span>
            <div class="label flex items-center">
                  <span
                      v-if="Number(record.reverseFlag) === 1"
                      class="reverse"
                  >反</span
                  >
              <span v-if="Number(record.moveFlag) === 1" class="move"
              >转</span
              >
              <span
                  v-if="Number(record.splitType) > 0 && record.children"
                  class="reverse"
              >AA</span
              >
            </div>
          </div>

        </template>
        <template v-else-if="column.dataIndex === 'tablePayDetails'">
          <template v-if="Number(record.freeFlag) === 1">
            {{ $t('免单') }}
          </template>
          <template v-else-if="record.splitType && record.children">
            --
          </template>
          <template
              v-else-if="record.tabStatus === OrderTabStatusEnum.Cancel"
          >
            --
          </template>
          <template v-else>
            <template v-for="(item, index) in record.tablePayDetails">
              {{ item.payMethodName }}:{{ formatMoney(item.payMoneyTotal) }}
              <template v-if="item.changeTotal > 0">
                ,{{ $t('找零') }}{{ formatMoney(item.changeTotal) }}
              </template>
              <template v-if="index < record.tablePayDetails.length - 1">
                ,
              </template>
            </template>
          </template>
        </template>
        <template v-else-if="column.dataIndex === 'tabStatus'">
          <div class="flex flex-col">
            <span> {{ getOrderStatus(record.tabStatus) }}</span>
            <span class="partial-flag">
                  {{ Number(record.partialFlag) ? $t('部分退') : '' }}
                </span>
          </div>
        </template>

        <template v-else-if="column.dataIndex === 'orgTotalPrice'">
          <span>
            {{ bridge.formatTotalPriceFh(record.orgTotalPrice)}}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'moneyTotal'">
          <span>
            {{ bridge.formatTotalPriceFh(record.moneyTotal)}}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'paymentTotal'">
          <span>
            {{ bridge.formatTotalPriceFh(record.paymentTotal)}}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'discountTotal'">
          <span>
            {{ bridge.formatTotalPriceFh(record.discountTotal)}}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'incomeTotal'">
          <span>
            {{ bridge.formatTotalPriceFh(record.incomeTotal)}}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'cashierName'">
          <span>
            {{record.cashierName || '--'}}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'payTime'">
          <span>
             {{record.payTime || '--'}}
          </span>
        </template>
      </template>
      <template #summary>
        <a-table-summary fixed>
          <a-table-summary-row>
            <a-table-summary-cell v-for="(item,index) in sums" style="background-color: #f9f9f9"
                                  :index="index">
              {{ item }}
            </a-table-summary-cell>
          </a-table-summary-row>
        </a-table-summary>
      </template>
    </a-table>

  </div>
</template>

<script setup>
import {ref} from "vue";
import {useI18n} from 'vue-i18n'
import {getOrderList} from "@/api/index.js";
import {cloneDeep} from 'lodash'
import dayjs from "dayjs";
import bridge from '@/utils/bridge'
import NP from 'number-precision'

const {t} = useI18n()
const loading = ref(false);
import {OrderTabStatusEnum, ClickTypeEnum} from '@/enums/order'

const currency = bridge.getCurrencyDefault() || '';

const formatMoney = (price) => {
  return bridge.formatTotalPriceFh(price);
}


const getOrderStatus = (status) => {
  const _status = Number(status)
  return _status === OrderTabStatusEnum.Unpay
      ? t('待结账')
      : status === OrderTabStatusEnum.Done
          ? t('已结账')
          : status === OrderTabStatusEnum.Return
              ? t('已退单')
              : status === OrderTabStatusEnum.Reverse
                  ? t('反结账')
                  : status === OrderTabStatusEnum.Cancel
                      ? t('已撤单')
                      : ''
}
const handleChange = (value) => {
  if (params.value.timeType === 3) {
    params.value.time = [
      dayjs().format('YYYY-MM-DD'),
      dayjs().format('YYYY-MM-DD')
    ]
  } else {
    params.value.time = [
      dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
  }
};
/** 订单状态 */
const options1 = ref([
  {
    value: 5,
    label: t('未结账'),
  },
  {
    value: 10,
    label: t('已结账'),
  },
  {
    value: 40,
    label: t('反结账'),
  },
  {
    value: 50,
    label: t('已撤单'),
  },
  {
    value: 30,
    label: t('已退单'),
  },
]);
const options2 = ref([
  {
    value: "",
    label: t('全部'),
  },
  {
    value: "POS",
    label: "POS",
  },
  {
    value: "PAD",
    label: "PAD",
  },
]);
const options3 = ref([
  {
    value: 1,
    label: t('下单时间'),
  },
  {
    value: 2,
    label: t('结账时间'),
  },
  {
    value: 3,
    label: t('营业日期'),
  },
]);
const options4 = ref([
  {
    value: "1",
    label: t('订单号'),
  },
  {
    value: "2",
    label: t('桌号'),
  },
  {
    value: "3",
    label: t('流水号'),
  },
]);

const data = ref([])

const columns = [
  {
    title: t('桌台'),
    dataIndex: 'tableName',
    fixed: 'left',
    width: 120
  },
  {
    title: t('订单号'),
    dataIndex: 'tableOpId',
    width: 160
  },
  {
    title: t('人数'),
    dataIndex: 'pepCount',
    width: 60
  },
  {
    title: t('订单金额') + currency,
    dataIndex: 'orgTotalPrice',
  },
  {
    title: t('顾客应付') + currency,
    dataIndex: 'moneyTotal',
  },
  {
    title: t('支付合计') + currency,
    dataIndex: 'paymentTotal',
  },
  {
    title: t('结账方式'),
    dataIndex: 'tablePayDetails',
  },
  {
    title: t('订单优惠') + currency,
    dataIndex: 'discountTotal',
  },
  {
    title: t('订单收入') + currency,
    dataIndex: 'incomeTotal',
  },
  {
    title: t('订单状态'),
    dataIndex: 'tabStatus',
    width: 80
  },
  {
    title: t('收银员'),
    dataIndex: 'cashierName',
    width: 80
  },
  {
    title: t('下单时间'),
    dataIndex: 'firstOrderTime',
    width: 140
  },
  {
    title: t('结账时间'),
    dataIndex: 'payTime',
    width: 140
  },
  {
    title: t('营业日期'),
    dataIndex: 'businessDate',
    width: 100
  },
  {
    title: t('操作'),
    dataIndex: 'oper',
    fixed: 'right',
    width: 200
  },
];

const handleReset = () => {
  params.value = cloneDeep(defaultParams)
  getList()
}
const defaultParams = {
  limit: 10000,
  page: 1,
  keywordType: '1',
  keyword: '',
  tabStatus: undefined,
  channel: undefined,
  time: [
    // dayjs('2025-04-01 10:23:05').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ],
  timeType: 1,
  startFirstOrderTime: '',
  endFirstOrderTime: '',
  posMacs: [],
  mealType: '',
  methodIds: [],
  cashierBys: [],
  diningTypes: [],
  invoiceTypes: []
}
const params = ref(cloneDeep(defaultParams))
const sums = ref([])

const clickListener = (record, type) => {
  bridge.clickListener(JSON.stringify(record), type)
}

function customRow(record, index) {
  return {
    onClick: () => {
      console.log('点击行：', record)
      clickListener(record, ClickTypeEnum.info)
    }
  }
}

const getSummaries = (data) => {
  sums.value = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums.value[index] = t('合计: 共')+data.length+t('单')
      return
    }
    if (
        [
          'tableOpId',
          'payOrderType',
          'tablePayDetails',
          'tabStatus',
          'cashierName',
          'firstOrderTime',
          'payTime',
          'businessDate',
          'oper'
        ].includes(column.dataIndex)
    ) {
      sums.value[index] = ''
      return
    }
    const values = data.map((item) => Number(item[column.dataIndex]))
    if (!values.every((value) => Number.isNaN(value))) {
      const total = `${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return NP.plus(prev, curr)
        } else {
          return prev
        }
      }, 0)}`
      sums.value[index] = formatMoney(total)
    } else {
      sums.value[index] = ''
    }
  })
}
const getList = async () => {
  if (loading.value){
    return;
  }
  loading.value = true;
  try {
    const [startFirstOrderTime, endFirstOrderTime] = params.value.time
    params.value.startFirstOrderTime = startFirstOrderTime
    params.value.endFirstOrderTime = endFirstOrderTime
    const res = await getOrderList(params.value)
    console.log('res', res.data)
    getSummaries(res.data)
    console.log('sums', sums)
    data.value = res.data.map((item, index) => {
      item.tabStatus = Number(item.tabStatus)
      item.splitType = Number(item.splitType)
      item.parentId = Number(item.parentId)

      if (item.splitType) {
        item.splitNum = item.childTableList?.length || 0
      }
      item.payMoneyTotal =
          item.tablePayDetails?.reduce((pre, cur) => {
            return pre + cur.payMoneyTotal
          }, 0) || 0
      item.children = item.childTableList
      item.childTableList?.forEach((child) => {
        if (item.splitType) {
          child.splitNum = item.childTableList?.length || 0
          child.parentId = item.tableOpId
        }
        child.tabStatus = Number(child.tabStatus)
        child.payMoneyTotal =
            child.tablePayDetails?.reduce((pre, cur) => {
              return pre + cur.payMoneyTotal
            }, 0) || 0
      })
      return item
    })
    loading.value = false;
  } catch (err) {
    console.error('列表获取失败', err)
    loading.value = false;
  }
}
window.callFromAndroid = function (data) {
  console.log('Android 调用 Vue 方法，收到数据：', data)
  // 可以调用 Vue 的方法或触发事件
  getList();
}
getList();
</script>

<style scoped>
.item {
  margin-right: 20px;
  margin-bottom: 10px;
}

.reverse {
  color: #FF5E4FFF;
  padding: 2px;
  font-size: 10px;
  background: rgba(255, 94, 79, 0.2);
  border-color: #FF5E4FFF;
  border-radius: 4px;
  border-style: solid;
  border-width: 1px;
  margin-left: 2px;
}

.partial-flag {
  text-decoration: underline;
  color: #1456f0;
}

:deep( .ant-table-summary) {
  background-color: #f9f9f9;
}
</style>